<?php
/**
 * Created by PhpStorm.
 * User: XZR
 * Date: 2018/8/1
 * Time: 15:21
 */

namespace Api\Controller;


//病历控制器

use Api\Model\CommentModel;
use Api\Model\MedicalRecordCollectModel;
use Api\Model\MedicalRecordDetailModel;
use Api\Model\MedicalRecordModel;
use Api\Model\UserModel;
use Api\Model\UserVoteModel;
use Api\Model\WeixinUserModel;
use Common\Service\WeChatService;
use Common\Util\ConfigUtils;
use Think\Log;

class RecordController extends AuthController
{
    //病历广场
    public function getList(){
        $this->validateParam(array("order_type"));
        $order_type = $this->getPostParam("order_type", "read_count");
        $query = $this->getPostParam("query",'');
        $pageno = $this->getPostParam("pageno", 1);
        $pageSize = $this->getPostParam("pagesize", 20);
        if ($order_type == 'my_collection') R('Record/myCollection');
        $rst = array();
        $rst['result']=200;
        $rst['list']=MedicalRecordModel::singleton()->getListByOrder($query,$order_type,$pageno,$pageSize,$this->userId);
        $this->formatjson($rst);
    }

    public function detail(){
        $this->validateParam(array("id"));
        $id  =$this->getPostParam("id");
        $row = MedicalRecordModel::singleton()->getOneById($id);
        if($row['visible']=='N'){
            $rst = array();
            $rst['result']=201;
            $rst['msg']='病历已删除';
            $this->formatjson($rst);
        }
        MedicalRecordModel::singleton()->incReadCount($id);//增加阅读数

        if($row){
            $row['eyelid_status']=unserialize($row['eyelid_status']);
            $row['past_history']=unserialize($row['past_history']);
            $doctor_info = UserModel::singleton()->getById($row['user_id']);
            $weixinInfo = WeixinUserModel::singleton()->getAvatarUrlByOpneid($doctor_info['openid']);
            $row['doctor']=$doctor_info['name'];
            $row['doctor_info']=[
                'name'=>$doctor_info['name'],
                'hospital'=>$doctor_info['hospital'],
                'title'=>$doctor_info['title'],
                'duty'=>$doctor_info['duty'],
                'avatarurl'=>$weixinInfo['avatarurl'],
                'nickname'=>$weixinInfo['nickname'],
            ];
            $row['avg_rate']=UserVoteModel::singleton()->getTotalRateByRecordId($id);
            $row['vote_count']=UserVoteModel::singleton()->getCountByRecordId($id);
            $vote = UserVoteModel::singleton()->getByUserIdAndRecordId($this->userId,$id);
            $rate = $vote['rate'];
            $row['vote_rate']=$rate;
            $row['is_vote']=$vote?1:0;
            $row['comment_list']=CommentModel::singleton()->getListByRecordId($id);//评论列表
/*            $share_data=[
                'commend_status'=>$row['comment_count']>0?1:0,
                'name'=>$doctor_info['name']." ".$doctor_info['duty']." ".$doctor_info['hospital'],
                'id'=>$row['id_number'],
                'age'=>$row['age'],
                'sex'=>$row['sex'],
                'clear'=>$row['myopia_year'].'年',
                'glass'=>$row['optician_year'].'年',
                'rate'=>$row['avg_rate'],
                'remark'=>$row['processing_results'],
                'new_comment_count'=>$row['new_comment_count']
            ];
            $row['share_image']=ConfigUtils::getConfig('SERVER_URL')."index.php?s=/Api/Image/index&data=".urlencode(base64_encode(json_encode($share_data)));*/
            $row['share_image']=ConfigUtils::getConfig('SERVER_URL')."index.php?s=/Api/Image/show&record_id=".$id."&timestamp=".time();
            $row['detail_list']=MedicalRecordDetailModel::singleton()->getListByRecordId($row['id']);
            $row['is_collect']=MedicalRecordCollectModel::singleton()->isCollect($this->userId,$id);
            $row['has_comment']=CommentModel::singleton()->hasComment($id);
            if (!$row['qr_code_url'] || $row['qr_code_url'] == ''){     // 若小程序码为空，则去生成小程序码
                try{
                    $result = (new WeChatService())->getMiniQrCode($id);
                    //print_r($result);
                    if ($result['status'] == 0){
                        Log::record("{$id} : " . $result['info']);
                        $row['qr_code_url'] =  "";
                        throw new \Exception('获取小程序码失败'.json_encode($result));
                    }
                    $row['qr_code_url'] = ConfigUtils::getConfig('SERVER_URL') . $result['info'];
                    MedicalRecordModel::singleton()->updateData($id, ['qr_code_url' => $row['qr_code_url']]);
                }catch (\Exception $e){
                    Log::record("{$id} : " . $e->getMessage());
                    $row['qr_code_url'] = "";
                }

            }
            $row['extra'] = json_decode($row['extra'], true);
            if (isset($row['extra']['basis_check_pic'])){
                $row['extra']['basis_check_pic'] = array_filter(explode(',', $row['extra']['basis_check_pic']));
                $row['extra']['basis_check_pic'] = $this->getImageSize($row['extra']['basis_check_pic']);
            }
            
        }
        $rst = array();
        $rst['result']=200;
        $rst['isself']=0;
        $rst['info']=$row;
        if($this->userId==$row['user_id']){
            $rst['isself']=1;
        }
        $this->formatjson($rst);
    }


    //我的病历
    public function commentList(){
        $this->validateParam(array("id"));
        $id  =$this->getPostParam("id");
        $rst['result']=200;
        $rst['list']=CommentModel::singleton()->getListByRecordId($id);
        $this->formatjson($rst);
    }



    //我的病历
    public function myRecordList(){
        $user_id=$this->userId;
        $pageno = $this->getPostParam("pageno", 1);
        $pageSize = $this->getPostParam("pagesize", 20);
        $rst = array();
        $rst['result']=200;
        $rst['list']=MedicalRecordModel::singleton()->getListByUserId($user_id,$pageno,$pageSize);
        $this->formatjson($rst);
    }

    //我的收藏
    public function myCollection(){
        $user_id=$this->userId;
        $pageno = $this->getPostParam("pageno", 1);
        $pageSize = $this->getPostParam("pagesize", 20);
        $rst = array();
        $rst['result']=200;
        $rst['list']=MedicalRecordModel::singleton()->getMyCollection($user_id,$pageno,$pageSize);
        $this->formatjson($rst);
    }

    public function create(){
        $data = $this->json();
        if(!$data){
            $rst = array();
            $rst['result']=202;
            $rst['msg']='缺少body数据';
            $this->formatjson($rst);
        }

        $rst = MedicalRecordModel::singleton()->addOrUpdate($data['id'],$data['data'],$this->userId);
        $this->formatjson($rst);

/*        $data=array(
            'id'=>1,
            'data'=>array(
                'age'=>18,
                'sex'=>1,
                'marriage_status'=>1,
                'occupation'=>'码农',
                'native_place'=>'广东广州',
                'wear_glasses'=>1,
                'wear_year'=>2,
                'stop_wear_week'=>20,
                'myopia_year'=>3,
                'optician_year'=>2,
                'mirror_od'=>300,
                'mirror_os'=>350,
                'diopte_change'=>100,
                'eyelid_status'=>array(
                    '上睑下垂','other'=>'AA'
                ),
                'past_history'=>array(
                    '干眼史','眼外伤',
                ),
                'patient_appeall'=>'XXXXXX',
                'processing_results'=>'XXXXX',
            )
        );
        echo json_encode($data);*/

    }

    //收藏/取消收藏
    public function collection(){
        $this->validateParam(array("record_id"));
        $record_id = $this->getPostParam("record_id", 0);
        $status = $this->getPostParam("status", 0);
        $user_id = $this->userId;
        $rst=MedicalRecordCollectModel::singleton()->collect($user_id,$record_id,$status);
        $this->formatjson($rst);
    }

    public function delete(){
        $this->validateParam(array("id"));//病历id
        $id = $this->getPostParam("id", 0);
        $rst = MedicalRecordModel::singleton()->deleteRecord($id,$this->userId);

        $this->formatjson($rst);
    }

    // 发布
    public function release(){
        $this->validateParam(array("id", "status"));
        $id  =$this->getPostParam("id");
        $user_id=$this->userId;
        $status = $this->getPostParam('status', 1);
        if (!in_array($status, [0,1])) return $this->formatjson(['result' => -2, 'msg' => '参数错误']);
        $rst = MedicalRecordModel::singleton()->release($id, $user_id, $status);

        $this->formatjson($rst);
    }

    public function share(){
        $this->validateParam(array("id"));//病历id
        $id = $this->getPostParam("id", 0);
        MedicalRecordModel::singleton()->incShareCount($id);

        $this->formatjson();
    }

    public function getImageSize($images){
        $Absolute_Path=$_SERVER['SCRIPT_FILENAME'];
        //截取index.php
        $Absolute_Path=substr($Absolute_Path,0,-9);

        $url = ConfigUtils::getConfig('SERVER_URL');

        $new_image = [];
        foreach ($images as $k => $v){
            $file_path = $Absolute_Path . str_replace($url, '', $v);
            $image_size = getimagesize($file_path) ;
            $new_image[] = [
                'url' => $v,
                'width' => $image_size[0],
                'height' => $image_size[1],
            ];
        }

        return $new_image;
    }

}